package com.naiterui.ehp.bs.im.network.mqtt.async;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.naiterui.ehp.bs.im.network.mqtt.handler.ClientStatusHandler;
import com.naiterui.ehp.bs.im.network.protocl.Event;
import com.naiterui.ehp.bs.im.utils.Constants;

public class ClientStatusCallback implements MqttCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(ClientStatusCallback.class);

    /**
     * 客户端状态操作类
     */
    private ClientStatusHandler clientStatusHandler;

    public ClientStatusCallback(ClientStatusHandler clientStatusHandler) {
        this.clientStatusHandler = clientStatusHandler;
    }

    @Override
    public void connectionLost(Throwable arg0) {
        // TODO Auto-generated method stub
    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {

        try {
            LOGGER.info("messageArrived INFO ; topic={}, message={}", topic, new String(mqttMessage.getPayload()));

            // 获取连接协议
            Event connection = clientStatusHandler.decode(new String(mqttMessage.getPayload()));

            // 类型不匹配
            if (connection.getC() == null || connection.getC() != Constants.EVENT_CAT_CONNECTION) {
                LOGGER.error("messageArrived ERROR ; type dismatch : topic={},message={}", topic, mqttMessage);
                return;
            }

            // 更改客户端在线状态
            clientStatusHandler.changeState(connection.getT(), connection.getI());

        } catch (Exception e) {
            LOGGER.error("messageArrived ERROR ; error={},topic={},message={}", e.getMessage(), topic, new String(mqttMessage.getPayload()), e, e);
        }
    }

}
